//
//  UserModel.m
//  sweet
//
//  Created by WTTT on 2023/7/10.
//

#import "UserModel.h"
#pragma mark - ==================数据本地化===========================
#define kUserDefaults       [NSUserDefaults standardUserDefaults]
//立即同步到文件
#define kSynchronize        [[NSUserDefaults standardUserDefaults] synchronize];

@implementation UserModel

#pragma mark - 单例
static UserModel *_instance;
static dispatch_once_t  onceToken;
static NSString *keyName = @"YUserModel";


+(instancetype)share
{
    dispatch_once(&onceToken, ^{
        if (_instance == nil) {
            _instance = [self loadLocalUserModel];
        }
    });
    return _instance;
}

-(id)copyWithZone:(NSZone *)zone
{
    return [UserModel share];
}
-(id)mutableCopyWithZone:(NSZone *)zone
{
    return [UserModel share];
}

// 加载本地的用户模型
+ (UserModel *)loadLocalUserModel {
    NSData *data = [kUserDefaults objectForKey:keyName];
    if (!data) {
        return [[self alloc]init];
    }
    return [UserModel yy_modelWithJSON:data];
}
#pragma mark - end

#pragma mark - 设置
// 重置单例
+ (void)resetUuserModel
{
    onceToken = 0;
    _instance = nil;
}

// 清除本地的所有用户数据
+ (void)clearLocalUserModel {
     
    // 重置用户单例
    [UserModel resetUuserModel];
    // 清空用户本地化缓存的数据
    [kUserDefaults removeObjectForKey:keyName];
   
    [kUserDefaults synchronize];
}

// 更新本地的用户数据
+ (void)updateLocalUserModel:(UserModel *)user
{
    // 将用户模型转换成json数据
    NSData *data = [user yy_modelToJSONData];
    // 将用户数据存储到本地
    [kUserDefaults setObject:data forKey:keyName];
    // 立即同步到文件
    kSynchronize;
    [UserModel resetUuserModel];
}

+ (NSDictionary *)mj_replacedKeyFromPropertyName
{
   return @{@"userid": @"id"};
}
 

//更新本地自己数据
+(void)SQ_updateLocal:(BaseModel*)model{
    UserModel * mo = [UserModel share];
    UserModel* mod = [UserModel mj_objectWithKeyValues:model.data];
    mod.token = mo.token;
    [UserModel updateLocalUserModel:mod];
}
 
@end
